import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import * as Global from '../../globals/global';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
})
export class HomeComponent {
  public isShow = true;
  public warnMsg: string;
  public loginID: string;
  public cityCode : string;
  public salary: string;
  public taxSalary = "0.00";
  public cityInfoList: CityInfoModel[];
 
  httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json; charset=utf-8'})
    ,withCredentials: true
  };

  constructor(private router: Router, private route : ActivatedRoute, private http: HttpClient) {
    this.http.get<CityInfoListModel>(Global.api.getCityInfo
      , this.httpOptions).subscribe(result => {  
        this.loginID = result.loginID;
        this.cityCode = result.defaultQueryCityCode;
        console.log(this.loginID);
        (!this.loginID) && (this.router.navigateByUrl("/login"));
        (!this.cityCode) && (this.cityCode = "0"); 
      this.cityInfoList = result.infoList;
    }, error => {
      console.error(error);
       this.router.navigateByUrl("/login");
    });
  }

  public calculate() {    

    if(this.cityCode == "0") {
      this.warnMsg = "Please select a city";
      this.isShow = true;
      return;
    }
    var nSala = Number.parseFloat(this.salary);
    if(isNaN(nSala) || nSala <= 0) {
      this.warnMsg = "Please input a valid salary";
      this.isShow = true;
      return;
    }

    this.warnMsg = "";
    this.isShow = false;
    //"loginID=" + this.loginID + "&cityCode=" + this.cityCode + "&salary=" + this.salary
    this.http.post<CalculateModel>(Global.api.calculateTaxSalary, {
      loginID: this.loginID,
      cityCode: this.cityCode,
      salary: this.salary
    }
      
      ,this.httpOptions).subscribe(result => {
      this.taxSalary = result.salary;
    }, error => error => {
      console.error(error);
       this.router.navigateByUrl("/login");
    });
  }  
  //"loginID=" + this.loginID
  logout() {
    this.http.post(Global.api.logout, {
      loginID: this.loginID
    }
    ,this.httpOptions).subscribe(result => {
        this.router.navigateByUrl("/login");
    }, error => error => {
      console.error(error);
       this.router.navigateByUrl("/login");
    });
  }
}

interface CityInfoListModel {
  loginID: string,
  defaultQueryCityCode: string,
  infoList: CityInfoModel[];
}

interface CityInfoModel {
  cityName: string;
  cityCode: string;
}

interface CalculateModel {
  salary : string
}
